﻿#define DebugOnly_X

#region Using Directives
using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using BarCodeDB.Entities;
using BarCodeDB.Services;
#endregion


namespace BarCodeDB.Website
{
    
    /// <summary>
    /// 
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {
        private string _DeCryptedPwd;
        private string _UserName;
        private string _UserDomain;
    
        /// <summary>
        /// Handles the Load event of the Page class.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //Request.RequestType = "POST";
            byte[] data = new byte[Request.InputStream.Length];
            string formID = "";
            string formName = "";
            BarcodeProcessor _AppUtil = new BarcodeProcessor();

            SFG.Common.Utilities.Encryptor _Encryptor = new SFG.Common.Utilities.Encryptor(SFG.Common.Utilities.Encryptor.SymmProvEnum.Rijndael);
            _DeCryptedPwd = _Encryptor.Decrypting(WebConfigurationManager.AppSettings["UserPwd"], WebConfigurationManager.AppSettings["EncryptKey"]);

            _UserName = WebConfigurationManager.AppSettings["UserAcct"];
            _UserDomain = WebConfigurationManager.AppSettings["UserDomain"];

            Request.InputStream.Read(data, 0, (int)Request.InputStream.Length);
            string str = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);

#if DebugOnly
            str = File.ReadAllText(Server.MapPath("~/Admin/FileDrop/Dummy.xml"), System.Text.Encoding.ASCII);
#endif
            BarCodeDB.Services.LaserAppMapsService _LAMS = new LaserAppMapsService();
            TList<BarCodeDB.Entities.LaserAppMaps> _LAM = null;

            if (Step1(ref formID, ref formName, _AppUtil, str, _LAMS, ref _LAM))
            {
                Step2(formID, formName, _AppUtil, str, _LAM);
            }
            else
            {
                Response.Write(_AppUtil.LaserAppErrorResponce(formID, "No Map found!"));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formID"></param>
        /// <param name="formName"></param>
        /// <param name="_AppUtil"></param>
        /// <param name="str"></param>
        /// <param name="_LAM"></param>
        private void Step2(string formID, string formName, BarcodeProcessor _AppUtil, string str, TList<BarCodeDB.Entities.LaserAppMaps> _LAM)
        {
            string _Path = String.Empty;
            _Path = WebConfigurationManager.AppSettings["FileDrop"] + "result.xml";
            FileStream fsResult = new FileStream(_Path, FileMode.Create, FileAccess.Write);
            
            StreamWriter swResult = null;
            string result = "";
            try
            {
                if (!String.IsNullOrEmpty(str) && _LAM.Count != 0)
                {
                    result = _AppUtil.BarCodeGenerator(str, WebConfigurationManager.AppSettings["FileDrop"]);
                    swResult = new StreamWriter(fsResult);
                    swResult.Write(result);
                }
                else
                {
                    result = _AppUtil.LaserAppErrorResponce(formID, "Error processing FORM:" + formName);
                }
            }
            catch (SystemException se)
            {
                result = _AppUtil.LaserAppErrorResponce(formID, "Error processing Form:" + se.Message + " - no map found");
            }
            finally
            {
                if (swResult != null)
                {
                    swResult.Flush();
                    swResult.Close();
                }

                if (fsResult != null)
                {
                    fsResult.Close();
                }
            }

            Response.Write(result);
            Response.End();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formID"></param>
        /// <param name="formName"></param>
        /// <param name="_AppUtil"></param>
        /// <param name="str"></param>
        /// <param name="_LAMS"></param>
        /// <param name="_LAM"></param>
        /// <returns></returns>
        private bool Step1(ref string formID, ref string formName, BarcodeProcessor _AppUtil, string str, BarCodeDB.Services.LaserAppMapsService _LAMS, ref TList<BarCodeDB.Entities.LaserAppMaps> _LAM)
        {
            bool retVal = true;
            XmlDocument xmlDoc = new XmlDocument();

            using (new SFG.Common.Utilities.Impersonator(_UserName, _UserDomain, _DeCryptedPwd))
            {
                if (!String.IsNullOrEmpty(str))
                {
                    xmlDoc.LoadXml(str);

                    _AppUtil.XMLDoc = xmlDoc;
                    formName = _AppUtil.GetFormName();

                    Guid _Guid = _AppUtil.GetFormID();
                    formID = _Guid.ToString();

                    _LAM = _LAMS.GetByFormNameMajorVerMinorVer(formName, int.Parse(_AppUtil.GetMajorVersionNbr()), int.Parse(_AppUtil.GetMinorVersionNbr()));

                    string xmlFilePath = WebConfigurationManager.AppSettings["FileDrop"] + formName + ".xml";
                    if (File.Exists(xmlFilePath))
                    {
                        File.Delete(xmlFilePath);
                    }

                    AppUtil.EncriptXmlDoc(ref xmlDoc);

                    xmlDoc.Save(xmlFilePath);
                }
                else
                {
                    retVal = false;
                }
            }
            return retVal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlDoc"></param>
        //private static void EncriptXmlDoc(ref XmlDocument xmlDoc)
        //{
        //    TripleDESCryptoServiceProvider tDESKey = new TripleDESCryptoServiceProvider();
        //    byte[] _Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
        //    tDESKey.Key = _Key;
        //    XmlElement FormElement = (XmlElement)xmlDoc.SelectSingleNode("/FORM");

        //    EncryptedXml exmlDoc = new EncryptedXml(xmlDoc);
        //    Byte[] encryptedForm = exmlDoc.EncryptData(FormElement, tDESKey, false);

        //    EncryptedData ed = new EncryptedData();
        //    ed.Type = EncryptedXml.XmlEncElementUrl;
        //    ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);
        //    ed.CipherData = new CipherData();
        //    ed.CipherData.CipherValue = encryptedForm;

        //    EncryptedXml.ReplaceElement(FormElement, ed, false);
        //}
    }
}
